import {v4} from "uuid"
import {now} from "../utils/time"
import loadFromStorage from "../utils/load-from-storage"
import {queryOne} from "./fake-db"

const token2Id = loadFromStorage('token2Id', {})
const id2Token = loadFromStorage('id2Token', {})

function loginAndGiveToken(user) {
    const token = v4()
    user.last_login_at = now()
    token2Id[token] = user.id
    id2Token[user.id] = token
    return token
}

function getLoggedUser() {
    const token = localStorage.getItem('token')
    if (!token) return undefined
    const id = token2Id[token]
    if (!id) return undefined
    if (id2Token[id] !== token) {
        delete id2Token[id]
        return undefined
    }
    const user = queryOne('user', 'id', id)
    if (!user || !user.enable) return undefined
    const role = queryOne('role', 'id', user.role)
    if (!role || !role.enable) {
        localStorage.removeItem('token')
        delete token2Id[token]
        delete id2Token[user.id]
        return undefined
    }
    return user
}

function logout() {
    const token = localStorage.getItem('token')
    localStorage.removeItem('token')
    if (token) {
        const id = token2Id[token]
        delete token2Id[token]
        if (id && id2Token[id] === token) {
            delete id2Token[id]
        }
    }
    if (window.location.pathname.startsWith('/main')) {
        window.location.assign('/start/login')
    }
}

export {loginAndGiveToken, getLoggedUser, logout}